package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.UacEmpMapper;
import com.csun.cmny.provider.dao.UacLifeActionEmpMapper;
import com.csun.cmny.provider.dao.UacUserMapper;
import com.csun.cmny.provider.model.constant.EmpConstant;
import com.csun.cmny.provider.model.constant.RoleConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.dept.EmpLifeDto;
import com.csun.cmny.provider.model.dto.dept.EmpQueryDto;
import com.csun.cmny.provider.model.dto.emp.UacEditEmpDto;
import com.csun.cmny.provider.model.dto.life.UacLifeDto;
import com.csun.cmny.provider.model.dto.user.BindUserRolesDto;
import com.csun.cmny.provider.model.enums.UacEmpStatusEnum;
import com.csun.cmny.provider.model.enums.UacUserSourceEnum;
import com.csun.cmny.provider.model.enums.UacUserTypeEnum;
import com.csun.cmny.provider.model.exceptions.UacBizException;
import com.csun.cmny.provider.model.vo.*;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.IdCardUtil;
import com.csun.cmny.provider.utils.Md5Util;
import com.csun.cmny.util.PublicUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2018-12-13 16:46
 * @Description:
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UacEmpServiceImpl extends BaseService<UacEmp> implements UacEmpService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UacUserService uacUserService;

    @Resource
    private UacGroupUserService uacGroupUserService;

    @Resource
    private UacEmpMapper uacEmpDao;

    @Resource
    private UacUserMapper uacUserDao;

    @Resource
    private UacRoleService uacRoleService;

    @Resource
    private UacRoleUserService uacRoleUserService;

    @Resource
    private UacUserTokenService uacUserTokenService;

    @Resource
    private OmcRpcService omcRpcService;

    @Resource
    private UacLifeActionEmpMapper uacLifeActionEmpMapper;

    @Resource
    private UacDeptService uacDeptService;

    /**
     * 根据deptId查询员工信息
     *
     * @param deptId 部门Id
     * @return 员工列表
     */
    @Override
    public List<EmpVo> getEmpByDeptId(Long deptId) {

        List<EmpVo> empVoList = uacEmpDao.getEmpByDeptId(deptId);

        return empVoList;
    }

    /**
     * 校验部门是否有员工
     *
     * @param deptId 部门Id
     * @return 校验结果
     */
    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public boolean checkDeptHasEmp(Long deptId) {

        Preconditions.checkArgument(deptId != null, "部门id不能为空.");

        UacEmp uacEmp = new UacEmp();
        uacEmp.setDeptId(deptId);

        return mapper.selectCount(uacEmp) > 0;
    }

    /**
     * 添加员工
     *
     * @param uacEditEmpDto 员工信息
     * @return 影响条数
     */
    @Override
    public int addUacEmp(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        UacUser uacUser = new UacUser();

        String loginName = uacEditEmpDto.getLoginName();
        String loginPwd = uacEditEmpDto.getLoginPwd();

        // 1.验证登录账号是否存在
        UacUser uacUserQuery = new UacUser();
        uacUserQuery.setLoginName(loginName);
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011045);
        }

        // 2.验证身份证号码是否已经存在
        uacUserQuery = new UacUser();
        uacUserQuery.setIdCard(uacEditEmpDto.getIdCard());
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011044);
        }

        /**
         * @desc: 校验手机号是否重复
         * @date: 2019-08-20
         * @author: chisj
         */
        if (!uacUserService.checkMobileNo(uacEditEmpDto.getMobileNo())) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        // 3.添加用户
        BeanUtils.copyProperties(uacEditEmpDto, uacUser);

        // 4.更新用户身份证信息(身份证, 性别, 年龄)
        setIdCard(uacUser);

        // 5.员工使用系统默认密码
        uacUser.setLoginPwd(Md5Util.encrypt(EmpConstant.EMP_DEFAULT_PWD));
        uacUser.setType(UacUserTypeEnum.GROUP_EMP.getKey());
        uacUser.setUserSource(UacUserSourceEnum.INSERT.getKey());
        uacUser.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacUser.setCreator(loginAuthDto.getUserName());
        uacUser.setCreatorId(loginAuthDto.getUserId());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        int result = uacUserDao.insertSelective(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 6.添加员工
        UacEmp uacEmp = new UacEmp();
        BeanUtils.copyProperties(uacEditEmpDto, uacEmp);

        uacEmp.setUserId(uacUser.getId());
        uacEmp.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacEmp.setCreator(loginAuthDto.getUserName());
        uacEmp.setCreatorId(loginAuthDto.getUserId());
        uacEmp.setLastOperator(loginAuthDto.getUserName());
        uacEmp.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.insertSelective(uacEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 3 绑定组织关系
        UacGroupUser uacGroupUser = new UacGroupUser();
        uacGroupUser.setGroupId(loginAuthDto.getGroupId());
        uacGroupUser.setUserId(uacUser.getId());
        uacGroupUserService.save(uacGroupUser);

        return result;
    }

    /**
     * 编辑员工
     *
     * @param uacEditEmpDto 员工信息
     * @return 影响条数
     */
    @Override
    public int editUacEmp(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        boolean isTokenRefresh = false;
        Long userId = uacEditEmpDto.getUserId();
        Preconditions.checkArgument(userId != null, "用户id不能为空.");

        Example example = new Example(UacUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("id", userId);

        UacUser uacUser = uacUserDao.selectByPrimaryKey(userId);
        Preconditions.checkArgument(uacUser != null, "用户不存在.");

        String loginName = uacUser.getLoginName();

        UacEmp uacEmpQuery = new UacEmp();
        uacEmpQuery.setUserId(userId);
        uacEmpQuery = uacEmpDao.selectOne(uacEmpQuery);
        Preconditions.checkArgument(uacEmpQuery != null, "员工不存在.");

        // 更新手机号
        if (StringUtils.isNoneEmpty(uacEditEmpDto.getMobileNo())
                && !uacEditEmpDto.getMobileNo().equals(uacUser.getMobileNo())) {
            // 校验手机号是否重复
            if (!uacUserService.checkMobileNo(userId, uacEditEmpDto.getMobileNo())) {
                throw new UacBizException(ErrorCodeEnum.UAC10011013);
            }
            uacUser.setMobileNo(uacEditEmpDto.getMobileNo());
        }
        // 更新登录账户
        if (StringUtils.isNoneEmpty(uacEditEmpDto.getLoginName())
                && !uacEditEmpDto.getLoginName().equals(uacUser.getLoginName())) {
            // 校验登录账号是否已经存在
            criteria.andEqualTo("loginName", uacEditEmpDto.getLoginName());
            int count = uacUserDao.selectCountByExample(example);
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011045);
            }
            uacUser.setLoginName(uacEditEmpDto.getLoginName());
            isTokenRefresh = true;
        }
        // 更新姓名
        if (StringUtils.isNoneEmpty(uacEditEmpDto.getUserName())) {
            uacUser.setUserName(uacEditEmpDto.getUserName());
        }
        // 更新用户身份证信息(身份证, 性别, 年龄)
        if (StringUtils.isNotEmpty(uacEditEmpDto.getIdCard())) {
            // 校验身份证号码是否已经存在
            example = new Example(UacUser.class);
            Example.Criteria criteriaIdCard = example.createCriteria();
            criteriaIdCard.andNotEqualTo("id", userId);
            criteriaIdCard.andEqualTo("idCard", uacEditEmpDto.getIdCard());
            int count = uacUserDao.selectCountByExample(example);
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011044);
            }

            uacUser.setIdCard(uacEditEmpDto.getIdCard());
            setIdCard(uacUser);
        }
        uacUser.setCreator(loginAuthDto.getUserName());
        uacUser.setCreatorId(loginAuthDto.getUserId());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        int result = uacUserDao.updateUacUser(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10011026, userId);
        }

        if (isTokenRefresh) {
            /**
             * @date    2019-09-04
             * @author  chisj
             * @desc    修改登录名后，刷新token
             */
            uacUserTokenService.restToken(loginName);
        }

        // 更新员工信息
        BeanUtils.copyProperties(uacEditEmpDto, uacEmpQuery);
        uacEmpQuery.setCreator(loginAuthDto.getUserName());
        uacEmpQuery.setCreatorId(loginAuthDto.getUserId());
        uacEmpQuery.setLastOperator(loginAuthDto.getUserName());
        uacEmpQuery.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.updateByUserId(uacEmpQuery);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017002, userId);
        }

        return result;
    }

    /**
     * 根据用户Id删除员工信息
     *
     * @param userId 用户Id
     * @return 影响条数
     */
    @Override
    public int deleteUacEmpByUserId(Long userId) {

        Preconditions.checkArgument(userId != null, "用户Id不能为空");

        // 1.校验用户是否为组织管理员
        UacRole uacRole = uacRoleService.findByRoleCode(RoleConstant.ROLD_CODE_ADMIN);
        if (PublicUtil.isNotEmpty(uacRole)) {
            UacRoleUser uacRoleUser = uacRoleUserService.getByUserIdAndRoleId(userId, uacRole.getId());
            if (PublicUtil.isNotEmpty(uacRoleUser)) {
                // 不能删除管理员
                throw new UacBizException(ErrorCodeEnum.UAC10017005, userId);
            }
        }

        // 2.获取当前员工信息
        UacEmp uacEmpQuery = new UacEmp();
        uacEmpQuery.setUserId(userId);
        uacEmpQuery = mapper.selectOne(uacEmpQuery);
        if (PublicUtil.isEmpty(uacEmpQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10017003, userId);
        }

        // 3.删除用户与组织关系
        UacGroupUser uacGroupUser = new UacGroupUser();
        uacGroupUser.setUserId(userId);
        uacGroupUserService.delete(uacGroupUser);

        // 4.删除用户
        UacUser uacUser = new UacUser();
        uacUser.setId(userId);
        uacUserService.delete(uacUser);

        // 5.删除员工信息
        int result = this.delete(uacEmpQuery);
        if (result < 1) {
            log.error("删除员工失败 userId={}", userId);
            throw new UacBizException(ErrorCodeEnum.UAC10017004, userId);
        }

        // 删除用户角色 -- 暂不处理

        return result;
    }

    /**
     * 根据userId查询员工信息
     *
     * @param userId 用户Id
     * @return 员工信息
     */
    @Override
    public EmpVo getUacEmpByUserId(Long userId) {

        Preconditions.checkArgument(userId != null, "用户id不能为空.");
        EmpVo empVo = uacEmpDao.getUacEmpByUserId(userId);
        if (PublicUtil.isEmpty(empVo)) {
            throw new UacBizException(ErrorCodeEnum.UAC10017003, userId);
        }

        return empVo;
    }

    /**
     * 查询员工信息列表 - 分页
     *
     * @param empQueryDto
     * @return
     */
    @Override
    public PageInfo queryEmpListWithPage(EmpQueryDto empQueryDto) {

        PageHelper.startPage(empQueryDto.getPageNum(), empQueryDto.getPageSize());

        List<EmpVo> empVoList = uacEmpDao.queryEmpListWithPage(empQueryDto);

        return new PageInfo(empVoList);
    }

    /**
     * 根据身份证设置年龄, 性别信息
     *
     * @param uacUser
     */
    public void setIdCard(UacUser uacUser) {

        try {
            // 根据身份证获取出生日期和性别
            Map<String, Object> map = null;
            if (uacUser.getIdCard().length() == 15) {
                // 校验15位
                String idCare = IdCardUtil.updateIDNo15to18(uacUser.getIdCard());
                if (!IdCardUtil.checkIDNo(idCare)) {
                    throw new UacBizException(ErrorCodeEnum.UAC10011046);
                }
                map = IdCardUtil.getCarInfo15W(uacUser.getIdCard());
            } else if (uacUser.getIdCard().length() == 18) {
                if (!IdCardUtil.checkIDNo(uacUser.getIdCard())) {
                    throw new UacBizException(ErrorCodeEnum.UAC10011046);
                }
                map = IdCardUtil.getCarInfo(uacUser.getIdCard());
            } else {
                throw new UacBizException(ErrorCodeEnum.UAC10011046);
            }
            if (map != null) {
                String birthday = (String) map.get("birthday");
                Integer sex = (Integer) map.get("sex");

                uacUser.setBirthday(birthday);
                uacUser.setSex(sex);
            }
        } catch (Exception e) {
            log.error("id card error: {}", e.getMessage());
            throw new UacBizException(ErrorCodeEnum.UAC10011046);
        }
    }

    @Override
    public int addUacEmpWithRole(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        UacUser uacUser = new UacUser();

        String loginName = uacEditEmpDto.getLoginName();
        String loginPwd = uacEditEmpDto.getLoginPwd();

        // 1.验证登录账号是否存在
        UacUser uacUserQuery = new UacUser();
        uacUserQuery.setLoginName(loginName);
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011045);
        }

        // 2.验证身份证号码是否已经存在
        uacUserQuery = new UacUser();
        uacUserQuery.setIdCard(uacEditEmpDto.getIdCard());
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011044);
        }

        /**
         * @desc: 校验手机号是否重复
         * @date: 2019-08-20
         * @author: chisj
         */
        if (!uacUserService.checkMobileNo(uacEditEmpDto.getMobileNo())) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        // 3.添加用户
        BeanUtils.copyProperties(uacEditEmpDto, uacUser);

        // 4.更新用户身份证信息(身份证, 性别, 年龄)
        setIdCard(uacUser);

        // 5.员工使用系统默认密码
        uacUser.setLoginPwd(Md5Util.encrypt(EmpConstant.EMP_DEFAULT_PWD));
        uacUser.setType(UacUserTypeEnum.GROUP_EMP.getKey());
        uacUser.setUserSource(UacUserSourceEnum.INSERT.getKey());
        uacUser.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacUser.setCreator(loginAuthDto.getUserName());
        uacUser.setCreatorId(loginAuthDto.getUserId());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        int result = uacUserDao.insertSelective(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 6.添加员工
        UacEmp uacEmp = new UacEmp();
        BeanUtils.copyProperties(uacEditEmpDto, uacEmp);

        uacEmp.setUserId(uacUser.getId());
        uacEmp.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacEmp.setCreator(loginAuthDto.getUserName());
        uacEmp.setCreatorId(loginAuthDto.getUserId());
        uacEmp.setLastOperator(loginAuthDto.getUserName());
        uacEmp.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.insertSelective(uacEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 3 绑定组织关系
        UacGroupUser uacGroupUser = new UacGroupUser();
        uacGroupUser.setGroupId(loginAuthDto.getGroupId());
        uacGroupUser.setUserId(uacUser.getId());
        uacGroupUserService.save(uacGroupUser);

        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacUser.getId());
        List<Long> roleIdList = new LinkedList<>();
        roleIdList.add(uacEditEmpDto.getRoleId());
        bindUserRolesDto.setRoleIdList(roleIdList);

        //绑定角色
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);

        return 1;
    }

    @Override
    public PageInfo queryUserListByEmpWithPage(EmpQueryDto empQueryDto) {

        PageHelper.startPage(empQueryDto.getPageNum(), empQueryDto.getPageSize());

        List<EmpVo> empVoList = uacEmpDao.queryUserListByEmpWithPage(empQueryDto);

        return new PageInfo(empVoList);
    }

    @Override
    public PageInfo selectUserListByEmpWithPage(EmpQueryDto empQueryDto) {

        PageHelper.startPage(empQueryDto.getPageNum(), empQueryDto.getPageSize());

        List<EmpRoleVo> empRoleVoList = uacEmpDao.selectUserListByEmpWithPage(empQueryDto);
        for (EmpRoleVo vo : empRoleVoList){
            List<RoleVo> role = uacRoleService.selectByUserId(vo.getUserId());
            vo.setRole(role);
        }
        return new PageInfo(empRoleVoList);
    }

    @Override
    public List<EmpVo> getEmpByDeptIdWithRole(Long deptId) {

        List<EmpVo> empVoList = uacEmpDao.getEmpByDeptIdWithRole(deptId);

        return empVoList;
    }

    @Override
    public int editUacEmpWithRole(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        int ret = editUacEmp(uacEditEmpDto,loginAuthDto);

        //查询用户角色
        UserBindRoleVo vo = uacUserService.getUserBindRoleDto(uacEditEmpDto.getUserId());

        //获取用户绑定的角色id
        Set<Long> userRoleIdList = vo.getAlreadyBindRoleIdSet();

        //护工调换角色时,删除用户绑定的护工 -- 若用户是班长不予删除
        for(Long id : userRoleIdList){
            UacRole role = uacRoleService.selectByKey(id);
            if(role != null){
                if(role.getRoleCode().equals("nursing")){
                    if(!uacEditEmpDto.getRoleId().equals(id)){
                        omcRpcService.deleteNursingUserBind(uacEditEmpDto.getUserId());
                    }
                }
            }
        }
        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacEditEmpDto.getUserId());
        List<Long> roleIdList = new LinkedList<>();
        roleIdList.add(uacEditEmpDto.getRoleId());
        bindUserRolesDto.setRoleIdList(roleIdList);

        //绑定角色
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);

        return ret;
    }

    @Override
    public EmpVo getUacEmpWithRoleByUserId(Long userId) {

        Preconditions.checkArgument(userId != null, "用户id不能为空.");
        EmpVo empVo = uacEmpDao.getUacEmpWithRoleByUserId(userId);
        if (PublicUtil.isEmpty(empVo)) {
            throw new UacBizException(ErrorCodeEnum.UAC10017003, userId);
        }

        return empVo;
    }

    @Override
    public int deleteUacEmpWithRoleByUserId(Long userId) {

        int ret = deleteUacEmpByUserId(userId);

        UacRoleUser uacRoleUserDelete = new UacRoleUser();
        uacRoleUserDelete.setUserId(userId);

        int result = uacRoleUserService.delete(uacRoleUserDelete);

        return ret;
    }

    @Override
    public PageInfo queryUserListByEmpWithLife(EmpLifeDto empLifeDto) {

        PageHelper.startPage(empLifeDto.getPageNum(), empLifeDto.getPageSize());

        List<EmpLifeVo> empVoList = uacEmpDao.queryUserListByEmpWithLife(empLifeDto);

        return new PageInfo(empVoList);
    }

    @Override
    public int addLifeUser(UacLifeDto uacLifeDto, LoginAuthDto loginAuthDto) {

        UacUser uacUser = new UacUser();
        UacEditEmpDto uacEditEmpDto = new UacEditEmpDto();
        uacEditEmpDto.setLoginName(uacLifeDto.getLoginName());
        String loginName = uacEditEmpDto.getLoginName();
        String loginPwd = uacEditEmpDto.getLoginPwd();

        // 1.验证登录账号是否存在
        UacUser uacUserQuery = new UacUser();
        uacUserQuery.setLoginName(loginName);
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011045);
        }

        // 5.员工使用系统默认密码
        uacUser.setLoginName(loginName);
        uacUser.setLoginPwd(Md5Util.encrypt(EmpConstant.EMP_DEFAULT_PWD));
        uacUser.setType(UacUserTypeEnum.GROUP_EMP.getKey());
        uacUser.setUserSource(UacUserSourceEnum.INSERT.getKey());
        uacUser.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacUser.setCreator(loginAuthDto.getUserName());
        uacUser.setCreatorId(loginAuthDto.getUserId());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        uacUser.setUserName(uacLifeDto.getFirstName()+uacLifeDto.getSecondName());
        int result = uacUserDao.insertSelective(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 6.添加员工
        UacEmp uacEmp = new UacEmp();
        BeanUtils.copyProperties(uacEditEmpDto, uacEmp);
        DeptVo vo =  uacDeptService.getDeptVoList(loginAuthDto.getGroupId());
        uacEmp.setDeptId(vo.getId());
        uacEmp.setUserId(uacUser.getId());
        uacEmp.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacEmp.setCreator(loginAuthDto.getUserName());
        uacEmp.setCreatorId(loginAuthDto.getUserId());
        uacEmp.setLastOperator(loginAuthDto.getUserName());
        uacEmp.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.insertSelective(uacEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 3 绑定组织关系
        UacGroupUser uacGroupUser = new UacGroupUser();
        uacGroupUser.setGroupId(loginAuthDto.getGroupId());
        uacGroupUser.setUserId(uacUser.getId());
        uacGroupUserService.save(uacGroupUser);

        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacUser.getId());
        List<Long> roleIdList = new LinkedList<>();
        roleIdList.add(uacLifeDto.getRoleId());
        bindUserRolesDto.setRoleIdList(roleIdList);
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);

        //添加life员工详情
        UacLifeActionEmp uacLifeActionEmp = new UacLifeActionEmp();
        uacLifeActionEmp.setEmpId(uacEmp.getId());
        uacLifeActionEmp.setFirstName(uacLifeDto.getFirstName());
        uacLifeActionEmp.setSecondName(uacLifeDto.getSecondName());
        uacLifeActionEmp.setSecFirstName(uacLifeDto.getSecFirstName());
        uacLifeActionEmp.setSecSecondName(uacLifeDto.getSecSecondName());
        uacLifeActionEmp.setActionName(uacLifeDto.getActionName());
        result = uacLifeActionEmpMapper.insert(uacLifeActionEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }
        return result;
    }

    @Override
    public int deleteLifeByUserId(Long userId) {
        LifeEmpVo lifeEmpVo = uacEmpDao.selectLifeUser(userId);
        int ret = deleteUacEmpByUserId(userId);

        UacRoleUser uacRoleUserDelete = new UacRoleUser();
        uacRoleUserDelete.setUserId(userId);

        int result = uacRoleUserService.delete(uacRoleUserDelete);
        if (result<1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017004, userId);
        }
        UacLifeActionEmp uacLifeActionEmp = new UacLifeActionEmp();
        uacLifeActionEmp.setEmpId(lifeEmpVo.getId());
        result = uacLifeActionEmpMapper.deleteByPrimaryKey(uacLifeActionEmp.getEmpId());
        if (result<1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017004, userId);
        }
        return ret;
    }

    @Override
    public LifeEmpVo selectLifeUser(Long userId){
        Preconditions.checkArgument(userId != null, "用户id不能为空.");
        LifeEmpVo lifeEmpVo = uacEmpDao.selectLifeUser(userId);
        if (PublicUtil.isEmpty(lifeEmpVo)) {
            throw new UacBizException(ErrorCodeEnum.UAC10017003, userId);
        }
        return lifeEmpVo;
    }

    @Override
    public Integer updateLifeUser(UacLifeDto uacLifeDto,LoginAuthDto loginAuthDto){
        boolean isTokenRefresh = false;
        Long userId = uacLifeDto.getUserId();
        Example example = new Example(UacUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("id", userId);
        UacUser uacUser = uacUserDao.selectByPrimaryKey(userId);
        String logName = uacUser.getLoginName();
        if (StringUtils.isNoneEmpty(uacLifeDto.getLoginName())
                && !uacLifeDto.getLoginName().equals(uacUser.getLoginName())) {
            // 校验登录账号是否已经存在
            criteria.andEqualTo("loginName", uacLifeDto.getLoginName());
            int count = uacUserDao.selectCountByExample(example);
            if (count > 0) {
                throw new UacBizException(ErrorCodeEnum.UAC10011045);
            }
            uacUser.setLoginName(uacLifeDto.getLoginName());
            isTokenRefresh = true;
        }
        // 更新用户表
        uacUser.setUserName(uacLifeDto.getFirstName()+uacLifeDto.getSecondName());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        int result = uacUserDao.updateUacUser(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017002, userId);
        }
        //更新员工表
        UacEmp uacEmp = new UacEmp();
        uacEmp.setUserId(userId);
        uacEmp = uacEmpDao.selectOne(uacEmp);
        uacEmp.setDeptId(uacDeptService.getDeptVoList(loginAuthDto.getGroupId()).getId());
        uacEmp.setLastOperator(loginAuthDto.getUserName());
        uacEmp.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.updateByUserId(uacEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017002, userId);
        }
        //根据userId重置token
        if (isTokenRefresh) {
            uacUserTokenService.restToken(logName);
        }
        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacLifeDto.getUserId());
        List<Long> roleIdList = new LinkedList<>();
        roleIdList.add(uacLifeDto.getRoleId());
        bindUserRolesDto.setRoleIdList(roleIdList);
        //绑定角色
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);
        //判断Life员工补充表是否存在该工作人员
        UacLifeActionEmp ue = new UacLifeActionEmp();
        ue.setEmpId(uacEmp.getId());
        ue = uacLifeActionEmpMapper.selectOne(ue);
        //life补充表所需参数
        UacLifeActionEmp uacLifeActionEmp = new UacLifeActionEmp();
        uacLifeActionEmp.setEmpId(uacEmp.getId());
        uacLifeActionEmp.setFirstName(uacLifeDto.getFirstName());
        uacLifeActionEmp.setSecondName(uacLifeDto.getSecondName());
        uacLifeActionEmp.setSecFirstName(uacLifeDto.getSecFirstName());
        uacLifeActionEmp.setSecSecondName(uacLifeDto.getSecSecondName());
        uacLifeActionEmp.setActionName(uacLifeDto.getActionName());
        if (PublicUtil.isEmpty(ue)){
            //添加life员工补充表
            uacLifeActionEmpMapper.insert(uacLifeActionEmp);
        }else {
            //更新Life员工补充表
            result = uacLifeActionEmpMapper.updateByPrimaryKey(uacLifeActionEmp);
            if (result < 1) {
                throw new UacBizException(ErrorCodeEnum.UAC10017002);
            }
        }
        return result;
    }

    @Override
    public int addUacEmpWithRoles(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        UacUser uacUser = new UacUser();

        String loginName = uacEditEmpDto.getLoginName();
        String loginPwd = uacEditEmpDto.getLoginPwd();

        // 1.验证登录账号是否存在
        UacUser uacUserQuery = new UacUser();
        uacUserQuery.setLoginName(loginName);
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011045);
        }

        // 2.验证身份证号码是否已经存在
        uacUserQuery = new UacUser();
        uacUserQuery.setIdCard(uacEditEmpDto.getIdCard());
        uacUserQuery = uacUserDao.selectOne(uacUserQuery);
        if (PublicUtil.isNotEmpty(uacUserQuery)) {
            throw new UacBizException(ErrorCodeEnum.UAC10011044);
        }

        /**
         * @desc: 校验手机号是否重复
         * @date: 2019-08-20
         * @author: chisj
         */
        if (!uacUserService.checkMobileNo(uacEditEmpDto.getMobileNo())) {
            throw new UacBizException(ErrorCodeEnum.UAC10011013);
        }

        // 3.添加用户
        BeanUtils.copyProperties(uacEditEmpDto, uacUser);

        // 4.更新用户身份证信息(身份证, 性别, 年龄)
        setIdCard(uacUser);

        // 5.员工使用系统默认密码
        uacUser.setLoginPwd(Md5Util.encrypt(EmpConstant.EMP_DEFAULT_PWD));
        uacUser.setType(UacUserTypeEnum.GROUP_EMP.getKey());
        uacUser.setUserSource(UacUserSourceEnum.INSERT.getKey());
        uacUser.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacUser.setCreator(loginAuthDto.getUserName());
        uacUser.setCreatorId(loginAuthDto.getUserId());
        uacUser.setLastOperator(loginAuthDto.getUserName());
        uacUser.setLastOperatorId(loginAuthDto.getUserId());
        int result = uacUserDao.insertSelective(uacUser);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 6.添加员工
        UacEmp uacEmp = new UacEmp();
        BeanUtils.copyProperties(uacEditEmpDto, uacEmp);

        uacEmp.setUserId(uacUser.getId());
        uacEmp.setStatus(UacEmpStatusEnum.ENABLE.getType());
        uacEmp.setCreator(loginAuthDto.getUserName());
        uacEmp.setCreatorId(loginAuthDto.getUserId());
        uacEmp.setLastOperator(loginAuthDto.getUserName());
        uacEmp.setLastOperatorId(loginAuthDto.getUserId());
        result = uacEmpDao.insertSelective(uacEmp);
        if (result < 1) {
            throw new UacBizException(ErrorCodeEnum.UAC10017001);
        }

        // 3 绑定组织关系
        UacGroupUser uacGroupUser = new UacGroupUser();
        uacGroupUser.setGroupId(loginAuthDto.getGroupId());
        uacGroupUser.setUserId(uacUser.getId());
        uacGroupUserService.save(uacGroupUser);

        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacUser.getId());
        bindUserRolesDto.setRoleIdList(uacEditEmpDto.getRoleIds());

        //绑定角色
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);

        return 1;
    }

    @Override
    public int editUacEmpWithRoles(UacEditEmpDto uacEditEmpDto, LoginAuthDto loginAuthDto) {

        int ret = editUacEmp(uacEditEmpDto,loginAuthDto);

        //查询用户角色
        UserBindRoleVo vo = uacUserService.getUserBindRoleDto(uacEditEmpDto.getUserId());

        //获取用户绑定的角色id
        Set<Long> userRoleIdList = vo.getAlreadyBindRoleIdSet();

        //护工调换角色时,删除用户绑定的护工 -- 若用户是班长不予删除
        for(Long id : userRoleIdList){
            UacRole role = uacRoleService.selectByKey(id);
            if(role != null){
                if(role.getRoleCode().equals("nursing")){
                    if(!uacEditEmpDto.getRoleId().equals(id)){
                        omcRpcService.deleteNursingUserBind(uacEditEmpDto.getUserId());
                    }
                }
            }
        }
        //创建用户、角色绑定对象
        BindUserRolesDto bindUserRolesDto = new BindUserRolesDto();
        bindUserRolesDto.setUserId(uacEditEmpDto.getUserId());

        bindUserRolesDto.setRoleIdList(uacEditEmpDto.getRoleIds());

        //绑定角色
        uacUserService.bindUserRoles(bindUserRolesDto,loginAuthDto);

        return ret;
    }
}
